import os
from typing import List, Dict, Optional, Union
from datetime import datetime, timedelta
from enum import Enum
from pydantic import BaseModel
from mcp.server.fastmcp import FastMCP

class ProductQuery(BaseModel):
    keywords: str
    category: Optional[str] = None
    location: Optional[str] = None
    min_price: Optional[float] = None
    max_price: Optional[float] = None

class Product(BaseModel):
    id: str
    name: str
    price: float
    description: str
    category: str
    store_location: Optional[str] = None
    stock: int
    rating: float
    sales: int

class Store(BaseModel):
    id: str
    name: str
    address: str
    location: str
    business_hours: str
    rating: float

# 添加优惠券数据模型
class Coupon(BaseModel):
    id: str
    code: str
    discount_type: str  # percentage/fixed
    discount_value: float
    min_purchase: float
    valid_categories: List[str]
    start_date: str
    end_date: str
    usage_limit: int
    used_count: int

# 添加评论数据模型
class Review(BaseModel):
    id: str
    product_id: str
    user_id: str
    rating: float
    content: str
    images: List[str]
    likes: int
    date: str

# 添加购物车数据模型
class CartItem(BaseModel):
    user_id: str
    product_id: str
    quantity: int
    selected: bool
    add_time: str

# 添加闪购活动数据模型
class FlashSale(BaseModel):
    id: str
    product_id: str
    original_price: float
    sale_price: float
    stock: int
    sold: int
    start_time: str
    end_time: str
    status: str  # upcoming/active/ended

# 添加用户画像数据模型
class UserProfile(BaseModel):
    user_id: str
    favorite_categories: List[str]
    price_sensitivity: float  # 0-1
    brand_preference: List[str]
    browse_history: List[str]
    purchase_history: List[str]
    last_active: str

class PaymentMethod(str, Enum):
    ALIPAY = "alipay"
    WECHAT = "wechat"
    CREDIT_CARD = "credit_card"
    BALANCE = "balance"

class OrderStatus(str, Enum):
    PENDING_PAYMENT = "pending_payment"
    PAID = "paid"
    SHIPPING = "shipping"
    DELIVERED = "delivered"
    COMPLETED = "completed"
    CANCELLED = "cancelled"
    REFUNDING = "refunding"
    REFUNDED = "refunded"

class Order(BaseModel):
    id: str
    user_id: str
    items: List[Dict]
    total_amount: float
    discount_amount: float
    final_amount: float
    status: OrderStatus
    payment_method: Optional[PaymentMethod]
    shipping_address: str
    shipping_fee: float
    create_time: str
    pay_time: Optional[str]
    ship_time: Optional[str]
    complete_time: Optional[str]

class WishList(BaseModel):
    user_id: str
    product_id: str
    add_time: str
    price_at_add: float
    note: Optional[str]

class SocialShare(BaseModel):
    id: str
    user_id: str
    product_id: str
    content: str
    images: List[str]
    likes: int
    comments: List[Dict]
    share_time: str

# 初始化 MCP 服务实例
mcp = FastMCP()

# 模拟商品数据库
MOCK_PRODUCTS = [
    Product(
        id="1",
        name="iPhone 15",
        price=6999.00,
        description="Apple最新旗舰手机，支持5G，A17芯片",
        category="手机数码",
        store_location="116.397428,39.909187",
        stock=100,
        rating=4.8,
        sales=1000
    ),
    Product(
        id="2",
        name="MacBook Pro",
        price=12999.00,
        description="专业级笔记本电脑，M2芯片",
        category="电脑办公",
        store_location="116.397428,39.909187",
        stock=50,
        rating=4.9,
        sales=500
    ),
    Product(
        id="3",
        name="AirPods Pro",
        price=1999.00,
        description="主动降噪无线耳机",
        category="手机数码",
        store_location="116.397428,39.909187",
        stock=200,
        rating=4.7,
        sales=2000
    )
]

# 模拟商品价格历史
PRICE_HISTORY = {
    "1": [
        {"date": "2024-01-01", "price": 7999.00},
        {"date": "2024-02-01", "price": 7499.00},
        {"date": "2024-03-01", "price": 6999.00}
    ]
}

# 模拟优惠券数据
MOCK_COUPONS = [
    Coupon(
        id="c1",
        code="NEWUSER20",
        discount_type="percentage",
        discount_value=20,
        min_purchase=100,
        valid_categories=["手机数码", "电脑办公"],
        start_date="2024-01-01",
        end_date="2024-12-31",
        usage_limit=1000,
        used_count=50
    ),
    Coupon(
        id="c2",
        code="TECH500",
        discount_type="fixed",
        discount_value=500,
        min_purchase=5000,
        valid_categories=["手机数码"],
        start_date="2024-03-01",
        end_date="2024-06-30",
        usage_limit=500,
        used_count=100
    )
]

# 模拟评论数据
MOCK_REVIEWS = [
    Review(
        id="r1",
        product_id="1",
        user_id="u1",
        rating=5.0,
        content="非常好用的手机，续航给力，相机效果出色！",
        images=["img1.jpg", "img2.jpg"],
        likes=120,
        date="2024-03-15"
    ),
    Review(
        id="r2",
        product_id="1",
        user_id="u2",
        rating=4.5,
        content="整体不错，就是价格稍贵",
        images=[],
        likes=50,
        date="2024-03-16"
    )
]

# 模拟购物车数据
MOCK_CART = {
    "u1": [
        CartItem(
            user_id="u1",
            product_id="1",
            quantity=1,
            selected=True,
            add_time="2024-03-20 10:00:00"
        )
    ]
}

# 模拟闪购活动数据
MOCK_FLASH_SALES = [
    FlashSale(
        id="fs1",
        product_id="1",
        original_price=6999.00,
        sale_price=5999.00,
        stock=50,
        sold=20,
        start_time="2024-03-20 10:00:00",
        end_time="2024-03-20 22:00:00",
        status="active"
    )
]

# 模拟用户画像数据
MOCK_USER_PROFILES = [
    UserProfile(
        user_id="u1",
        favorite_categories=["手机数码", "电脑办公"],
        price_sensitivity=0.8,
        brand_preference=["Apple", "Samsung"],
        browse_history=["1", "2", "3"],
        purchase_history=["1"],
        last_active="2024-03-20 15:00:00"
    )
]

# 模拟订单数据
MOCK_ORDERS = [
    Order(
        id="o1",
        user_id="u1",
        items=[{"product_id": "1", "quantity": 1, "price": 6999.00}],
        total_amount=6999.00,
        discount_amount=500.00,
        final_amount=6499.00,
        status=OrderStatus.COMPLETED,
        payment_method=PaymentMethod.ALIPAY,
        shipping_address="北京市朝阳区三里屯",
        shipping_fee=0.00,
        create_time="2024-03-15 10:00:00",
        pay_time="2024-03-15 10:05:00",
        ship_time="2024-03-16 10:00:00",
        complete_time="2024-03-18 15:00:00"
    )
]

# 模拟心愿单数据
MOCK_WISHLISTS = [
    WishList(
        user_id="u1",
        product_id="2",
        add_time="2024-03-15 10:00:00",
        price_at_add=12999.00,
        note="等降价"
    )
]

# 模拟社交分享数据
MOCK_SHARES = [
    SocialShare(
        id="s1",
        user_id="u1",
        product_id="1",
        content="iPhone 15真的很好用！",
        images=["share1.jpg"],
        likes=50,
        comments=[
            {"user_id": "u2", "content": "同意！", "time": "2024-03-19 10:00:00"}
        ],
        share_time="2024-03-19 09:00:00"
    )
]

@mcp.tool()
def search_products(keywords: str, category: str = None, location: str = None,
                   min_price: float = None, max_price: float = None,
                   sort_by: str = "relevance") -> Dict:
    """
    高级商品搜索
    :param keywords: 搜索关键词
    :param category: 商品类别
    :param location: 位置信息
    :param min_price: 最低价格
    :param max_price: 最高价格
    :param sort_by: 排序方式(relevance/price_asc/price_desc/sales/rating)
    :return: 搜索结果
    """
    results = []
    for product in MOCK_PRODUCTS:
        if keywords.lower() in product.name.lower() or keywords.lower() in product.description.lower():
            if category and category != product.category:
                continue
            if min_price is not None and product.price < min_price:
                continue
            if max_price is not None and product.price > max_price:
                continue
            results.append(product.dict())
    
    # 排序
    if sort_by == "price_asc":
        results.sort(key=lambda x: x["price"])
    elif sort_by == "price_desc":
        results.sort(key=lambda x: x["price"], reverse=True)
    elif sort_by == "sales":
        results.sort(key=lambda x: x["sales"], reverse=True)
    elif sort_by == "rating":
        results.sort(key=lambda x: x["rating"], reverse=True)
    
    return {
        "total": len(results),
        "products": results
    }

@mcp.tool()
def get_product_detail(product_id: str) -> Dict:
    """
    获取商品详情
    :param product_id: 商品ID
    :return: 商品详情
    """
    for product in MOCK_PRODUCTS:
        if product.id == product_id:
            result = product.dict()
            # 添加价格历史
            if product_id in PRICE_HISTORY:
                result["price_history"] = PRICE_HISTORY[product_id]
            # 获取商品所在店铺信息
            if product.store_location:
                try:
                    store_info = find_store_by_location(product.store_location)
                    result["store_info"] = store_info
                except Exception:
                    pass
            return result
    return {"error": "商品不存在"}

@mcp.tool()
def find_nearby_stores(location: str, radius: int = 3000) -> Dict:
    """
    查找附近的实体店
    :param location: 位置坐标（经度,纬度）
    :param radius: 搜索半径（米）
    :return: 附近商店列表
    """
    try:
        return {
            "tool": "mcp_amap_amap_sse_maps_around_search",
            "params": {
                "keywords": "商场|购物中心|百货",
                "location": location,
                "radius": str(radius)
            }
        }
    except Exception as e:
        return {"error": f"查询失败: {str(e)}"}

@mcp.tool()
def get_store_route(user_location: str, store_location: str, transport_mode: str = "driving") -> Dict:
    """
    获取到店路线
    :param user_location: 用户位置坐标
    :param store_location: 商店位置坐标
    :param transport_mode: 出行方式(driving/walking/bicycling/transit)
    :return: 路线规划信息
    """
    try:
        if transport_mode == "driving":
            return {
                "tool": "mcp_amap_amap_sse_maps_direction_driving",
                "params": {
                    "origin": user_location,
                    "destination": store_location
                }
            }
        elif transport_mode == "walking":
            return {
                "tool": "mcp_amap_amap_sse_maps_direction_walking",
                "params": {
                    "origin": user_location,
                    "destination": store_location
                }
            }
        elif transport_mode == "bicycling":
            return {
                "tool": "mcp_amap_amap_sse_maps_direction_bicycling",
                "params": {
                    "origin": user_location,
                    "destination": store_location
                }
            }
        else:
            return {"error": "不支持的出行方式"}
    except Exception as e:
        return {"error": f"路线规划失败: {str(e)}"}

@mcp.tool()
def get_shopping_recommendation(budget: float = None, category: str = None, 
                             user_location: str = None, preferences: List[str] = None) -> Dict:
    """
    获取智能购物建议
    :param budget: 预算
    :param category: 商品类别
    :param user_location: 用户位置
    :param preferences: 用户偏好标签列表
    :return: 推荐商品列表
    """
    recommendations = []
    for product in MOCK_PRODUCTS:
        score = 0
        # 预算匹配度
        if budget and product.price <= budget:
            score += 5
        # 类别匹配度
        if category and product.category == category:
            score += 3
        # 好评度
        score += product.rating
        # 销量权重
        score += min(product.sales / 1000, 5)
        
        if score > 0:
            recommendation = product.dict()
            recommendation["match_score"] = score
            recommendations.append(recommendation)
    
    # 按匹配度排序
    recommendations.sort(key=lambda x: x["match_score"], reverse=True)
    
    return {
        "total": len(recommendations),
        "recommendations": recommendations[:5]  # 返回前5个最佳推荐
    }

@mcp.tool()
def analyze_price_trend(product_id: str) -> Dict:
    """
    分析商品价格趋势
    :param product_id: 商品ID
    :return: 价格分析结果
    """
    if product_id not in PRICE_HISTORY:
        return {"error": "无价格历史数据"}
    
    history = PRICE_HISTORY[product_id]
    prices = [item["price"] for item in history]
    current_price = next((p.price for p in MOCK_PRODUCTS if p.id == product_id), None)
    
    if not current_price:
        return {"error": "商品不存在"}
    
    highest_price = max(prices)
    lowest_price = min(prices)
    avg_price = sum(prices) / len(prices)
    
    return {
        "current_price": current_price,
        "highest_price": highest_price,
        "lowest_price": lowest_price,
        "average_price": avg_price,
        "price_trend": "上涨" if current_price > avg_price else "下跌",
        "price_history": history,
        "buy_advice": "建议购买" if current_price <= avg_price else "建议等待"
    }

@mcp.tool()
def find_store_by_location(location: str) -> Dict:
    """
    根据位置获取商店信息
    :param location: 位置坐标
    :return: 商店信息
    """
    try:
        return {
            "tool": "mcp_amap_amap_sse_maps_regeocode",
            "params": {
                "location": location
            }
        }
    except Exception as e:
        return {"error": f"获取商店信息失败: {str(e)}"}

@mcp.tool()
def compare_products(product_ids: List[str]) -> Dict:
    """
    商品对比功能
    :param product_ids: 要对比的商品ID列表
    :return: 对比结果
    """
    if len(product_ids) < 2:
        return {"error": "至少需要两个商品进行对比"}
    
    products = []
    for pid in product_ids:
        product = next((p for p in MOCK_PRODUCTS if p.id == pid), None)
        if product:
            products.append(product)
    
    if len(products) < 2:
        return {"error": "部分商品不存在"}
    
    comparison = {
        "basic_info": [],
        "price_comparison": {
            "highest": max(p.price for p in products),
            "lowest": min(p.price for p in products),
            "average": sum(p.price for p in products) / len(products)
        },
        "rating_comparison": {
            "highest": max(p.rating for p in products),
            "lowest": min(p.rating for p in products),
            "average": sum(p.rating for p in products) / len(products)
        },
        "features_comparison": []
    }
    
    for product in products:
        comparison["basic_info"].append({
            "id": product.id,
            "name": product.name,
            "price": product.price,
            "rating": product.rating,
            "sales": product.sales,
            "stock": product.stock
        })
    
    return comparison

@mcp.tool()
def get_available_coupons(product_id: str, total_amount: float) -> Dict:
    """
    获取可用优惠券
    :param product_id: 商品ID
    :param total_amount: 订单总金额
    :return: 可用优惠券列表
    """
    product = next((p for p in MOCK_PRODUCTS if p.id == product_id), None)
    if not product:
        return {"error": "商品不存在"}
    
    available_coupons = []
    current_date = datetime.now().strftime("%Y-%m-%d")
    
    for coupon in MOCK_COUPONS:
        if (coupon.start_date <= current_date <= coupon.end_date and
            coupon.used_count < coupon.usage_limit and
            total_amount >= coupon.min_purchase and
            (not coupon.valid_categories or product.category in coupon.valid_categories)):
            
            # 计算优惠金额
            if coupon.discount_type == "percentage":
                discount_amount = total_amount * (coupon.discount_value / 100)
            else:
                discount_amount = coupon.discount_value
            
            coupon_info = coupon.dict()
            coupon_info["discount_amount"] = discount_amount
            coupon_info["final_price"] = total_amount - discount_amount
            available_coupons.append(coupon_info)
    
    return {
        "total": len(available_coupons),
        "coupons": available_coupons
    }

@mcp.tool()
def get_product_reviews(product_id: str, sort_by: str = "date") -> Dict:
    """
    获取商品评论
    :param product_id: 商品ID
    :param sort_by: 排序方式(date/likes/rating)
    :return: 评论列表
    """
    reviews = [r for r in MOCK_REVIEWS if r.product_id == product_id]
    
    if sort_by == "likes":
        reviews.sort(key=lambda x: x.likes, reverse=True)
    elif sort_by == "rating":
        reviews.sort(key=lambda x: x.rating, reverse=True)
    else:  # default: date
        reviews.sort(key=lambda x: x.date, reverse=True)
    
    # 计算评分统计
    if reviews:
        ratings = [r.rating for r in reviews]
        rating_stats = {
            "average": sum(ratings) / len(ratings),
            "total": len(ratings),
            "distribution": {
                "5": len([r for r in ratings if r == 5.0]),
                "4": len([r for r in ratings if 4.0 <= r < 5.0]),
                "3": len([r for r in ratings if 3.0 <= r < 4.0]),
                "2": len([r for r in ratings if 2.0 <= r < 3.0]),
                "1": len([r for r in ratings if r < 2.0])
            }
        }
    else:
        rating_stats = {"error": "暂无评论"}
    
    return {
        "total": len(reviews),
        "rating_stats": rating_stats,
        "reviews": [r.dict() for r in reviews]
    }

@mcp.tool()
def get_similar_products(product_id: str, limit: int = 5) -> Dict:
    """
    获取相似商品推荐
    :param product_id: 商品ID
    :param limit: 返回数量
    :return: 相似商品列表
    """
    product = next((p for p in MOCK_PRODUCTS if p.id == product_id), None)
    if not product:
        return {"error": "商品不存在"}
    
    # 基于类别和价格范围查找相似商品
    similar_products = []
    price_range = (product.price * 0.7, product.price * 1.3)  # 价格范围±30%
    
    for p in MOCK_PRODUCTS:
        if p.id != product_id and p.category == product.category:
            if price_range[0] <= p.price <= price_range[1]:
                similarity_score = 0
                # 价格相似度
                price_diff_percent = abs(p.price - product.price) / product.price
                similarity_score += (1 - price_diff_percent) * 5
                # 评分相似度
                rating_diff = abs(p.rating - product.rating)
                similarity_score += (5 - rating_diff)
                
                similar_product = p.dict()
                similar_product["similarity_score"] = similarity_score
                similar_products.append(similar_product)
    
    # 按相似度排序
    similar_products.sort(key=lambda x: x["similarity_score"], reverse=True)
    
    return {
        "total": len(similar_products),
        "products": similar_products[:limit]
    }

@mcp.tool()
def analyze_shopping_trends(category: str = None, days: int = 30) -> Dict:
    """
    分析购物趋势
    :param category: 商品类别
    :param days: 统计天数
    :return: 趋势分析结果
    """
    products = MOCK_PRODUCTS
    if category:
        products = [p for p in products if p.category == category]
    
    if not products:
        return {"error": "无相关商品数据"}
    
    # 分析价格趋势
    avg_price = sum(p.price for p in products) / len(products)
    price_range = {
        "lowest": min(p.price for p in products),
        "highest": max(p.price for p in products),
        "average": avg_price
    }
    
    # 分析销量趋势
    total_sales = sum(p.sales for p in products)
    avg_sales = total_sales / len(products)
    
    # 热门商品
    hot_products = sorted(products, key=lambda x: x.sales, reverse=True)[:3]
    
    return {
        "category": category or "全部",
        "period": f"近{days}天",
        "price_analysis": price_range,
        "sales_analysis": {
            "total_sales": total_sales,
            "average_sales": avg_sales
        },
        "hot_products": [
            {
                "id": p.id,
                "name": p.name,
                "price": p.price,
                "sales": p.sales
            } for p in hot_products
        ]
    }

@mcp.tool()
def calculate_shipping_cost(product_ids: List[str], address: str) -> Dict:
    """
    计算运费
    :param product_ids: 商品ID列表
    :param address: 收货地址
    :return: 运费计算结果
    """
    try:
        # 获取地址的经纬度
        location_info = {
            "tool": "mcp_amap_amap_sse_maps_geo",
            "params": {
                "address": address
            }
        }
        
        # 基础运费计算（示例）
        total_weight = 0
        products = []
        
        for pid in product_ids:
            product = next((p for p in MOCK_PRODUCTS if p.id == pid), None)
            if product:
                products.append(product)
                total_weight += 1  # 假设每个商品重1kg
        
        if not products:
            return {"error": "商品不存在"}
        
        # 简单运费计算规则
        base_fee = 10  # 基础运费
        weight_fee = total_weight * 2  # 重量费用
        
        return {
            "products": [{"id": p.id, "name": p.name} for p in products],
            "address": address,
            "weight": total_weight,
            "base_fee": base_fee,
            "weight_fee": weight_fee,
            "total_fee": base_fee + weight_fee,
            "location_info": location_info
        }
    except Exception as e:
        return {"error": f"运费计算失败: {str(e)}"}

@mcp.tool()
def manage_shopping_cart(user_id: str, action: str, product_id: str = None, quantity: int = 1) -> Dict:
    """
    购物车管理
    :param user_id: 用户ID
    :param action: 操作类型(add/remove/update/list/clear)
    :param product_id: 商品ID
    :param quantity: 商品数量
    :return: 购物车信息
    """
    if user_id not in MOCK_CART:
        MOCK_CART[user_id] = []
    
    if action == "add":
        # 检查商品是否存在
        product = next((p for p in MOCK_PRODUCTS if p.id == product_id), None)
        if not product:
            return {"error": "商品不存在"}
        
        # 检查是否已在购物车中
        cart_item = next((item for item in MOCK_CART[user_id] if item.product_id == product_id), None)
        if cart_item:
            cart_item.quantity += quantity
        else:
            MOCK_CART[user_id].append(
                CartItem(
                    user_id=user_id,
                    product_id=product_id,
                    quantity=quantity,
                    selected=True,
                    add_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                )
            )
    elif action == "remove":
        MOCK_CART[user_id] = [item for item in MOCK_CART[user_id] if item.product_id != product_id]
    elif action == "update":
        cart_item = next((item for item in MOCK_CART[user_id] if item.product_id == product_id), None)
        if cart_item:
            cart_item.quantity = quantity
    elif action == "clear":
        MOCK_CART[user_id] = []
    
    # 计算购物车总价
    total_price = 0
    cart_items = []
    for item in MOCK_CART[user_id]:
        product = next((p for p in MOCK_PRODUCTS if p.id == item.product_id), None)
        if product:
            item_info = item.dict()
            item_info["product"] = product.dict()
            item_info["subtotal"] = product.price * item.quantity
            total_price += item_info["subtotal"]
            cart_items.append(item_info)
    
    return {
        "user_id": user_id,
        "items": cart_items,
        "total_price": total_price,
        "item_count": len(cart_items)
    }

@mcp.tool()
def get_flash_sales(status: str = "active") -> Dict:
    """
    获取闪购活动
    :param status: 活动状态(upcoming/active/ended)
    :return: 闪购活动列表
    """
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    sales = []
    for sale in MOCK_FLASH_SALES:
        if status == "active" and sale.start_time <= current_time <= sale.end_time:
            sales.append(sale.dict())
        elif status == "upcoming" and sale.start_time > current_time:
            sales.append(sale.dict())
        elif status == "ended" and sale.end_time < current_time:
            sales.append(sale.dict())
    
    return {
        "total": len(sales),
        "sales": sales
    }

@mcp.tool()
def get_personalized_recommendations(user_id: str) -> Dict:
    """
    获取个性化推荐
    :param user_id: 用户ID
    :return: 推荐商品列表
    """
    user = next((u for u in MOCK_USER_PROFILES if u.user_id == user_id), None)
    if not user:
        return {"error": "用户不存在"}
    
    recommendations = []
    for product in MOCK_PRODUCTS:
        score = 0
        # 类别匹配
        if product.category in user.favorite_categories:
            score += 3
        # 价格敏感度
        if product.price < 1000 and user.price_sensitivity > 0.7:
            score += 2
        # 浏览历史
        if product.id in user.browse_history:
            score += 1
        
        if score > 0:
            rec = product.dict()
            rec["match_score"] = score
            recommendations.append(rec)
    
    recommendations.sort(key=lambda x: x["match_score"], reverse=True)
    
    return {
        "user_id": user_id,
        "total": len(recommendations),
        "recommendations": recommendations[:5]
    }

@mcp.tool()
def track_user_behavior(user_id: str, action: str, product_id: str) -> Dict:
    """
    追踪用户行为
    :param user_id: 用户ID
    :param action: 行为类型(view/like/add_to_cart/purchase)
    :param product_id: 商品ID
    :return: 更新后的用户画像
    """
    user = next((u for u in MOCK_USER_PROFILES if u.user_id == user_id), None)
    if not user:
        return {"error": "用户不存在"}
    
    product = next((p for p in MOCK_PRODUCTS if p.id == product_id), None)
    if not product:
        return {"error": "商品不存在"}
    
    # 更新用户画像
    if action == "view":
        if product_id not in user.browse_history:
            user.browse_history.append(product_id)
    elif action == "purchase":
        if product_id not in user.purchase_history:
            user.purchase_history.append(product_id)
        if product.category not in user.favorite_categories:
            user.favorite_categories.append(product.category)
    
    user.last_active = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    return user.dict()

@mcp.tool()
def create_price_alert(user_id: str, product_id: str, target_price: float) -> Dict:
    """
    创建降价提醒
    :param user_id: 用户ID
    :param product_id: 商品ID
    :param target_price: 目标价格
    :return: 提醒设置结果
    """
    product = next((p for p in MOCK_PRODUCTS if p.id == product_id), None)
    if not product:
        return {"error": "商品不存在"}
    
    # 检查闪购活动
    flash_sale = next((s for s in MOCK_FLASH_SALES if s.product_id == product_id), None)
    
    alert_info = {
        "user_id": user_id,
        "product": product.dict(),
        "target_price": target_price,
        "current_price": product.price,
        "price_diff": product.price - target_price,
        "status": "waiting"
    }
    
    if flash_sale and flash_sale.sale_price <= target_price:
        alert_info["status"] = "available"
        alert_info["flash_sale"] = flash_sale.dict()
    
    return alert_info

@mcp.tool()
def get_promotion_strategy(product_ids: List[str], total_amount: float) -> Dict:
    """
    获取促销方案
    :param product_ids: 商品ID列表
    :param total_amount: 总金额
    :return: 促销方案
    """
    available_promotions = []
    
    # 满减促销
    if total_amount >= 10000:
        available_promotions.append({
            "type": "amount_off",
            "description": "满10000减1000",
            "discount": 1000
        })
    elif total_amount >= 5000:
        available_promotions.append({
            "type": "amount_off",
            "description": "满5000减500",
            "discount": 500
        })
    
    # 第二件半价
    products = [p for p in MOCK_PRODUCTS if p.id in product_ids]
    if len(products) >= 2:
        available_promotions.append({
            "type": "second_half",
            "description": "第二件半价",
            "discount": min(p.price for p in products) * 0.5
        })
    
    # 组合优惠
    categories = set(p.category for p in products)
    if len(categories) >= 2:
        available_promotions.append({
            "type": "bundle",
            "description": "跨品类优惠200",
            "discount": 200
        })
    
    # 计算最大优惠
    if available_promotions:
        max_discount = max(p["discount"] for p in available_promotions)
        best_promotion = next(p for p in available_promotions if p["discount"] == max_discount)
    else:
        best_promotion = None
    
    return {
        "total_amount": total_amount,
        "available_promotions": available_promotions,
        "best_promotion": best_promotion,
        "final_amount": total_amount - (max_discount if available_promotions else 0)
    }

@mcp.tool()
def create_order(user_id: str, cart_items: List[Dict], shipping_address: str) -> Dict:
    """
    创建订单
    :param user_id: 用户ID
    :param cart_items: 购物车商品列表
    :param shipping_address: 收货地址
    :return: 订单信息
    """
    # 计算订单金额
    total_amount = 0
    order_items = []
    
    for item in cart_items:
        product = next((p for p in MOCK_PRODUCTS if p.id == item["product_id"]), None)
        if not product:
            return {"error": f"商品不存在: {item['product_id']}"}
        if product.stock < item["quantity"]:
            return {"error": f"商品库存不足: {product.name}"}
        
        item_total = product.price * item["quantity"]
        total_amount += item_total
        order_items.append({
            "product_id": product.id,
            "quantity": item["quantity"],
            "price": product.price
        })
    
    # 获取促销方案
    promotion = get_promotion_strategy(
        product_ids=[item["product_id"] for item in cart_items],
        total_amount=total_amount
    )
    
    # 计算运费
    shipping_info = calculate_shipping_cost(
        product_ids=[item["product_id"] for item in cart_items],
        address=shipping_address
    )
    
    # 创建订单
    order = Order(
        id=f"o{len(MOCK_ORDERS)+1}",
        user_id=user_id,
        items=order_items,
        total_amount=total_amount,
        discount_amount=promotion.get("best_promotion", {}).get("discount", 0),
        final_amount=promotion.get("final_amount", total_amount) + shipping_info.get("total_fee", 0),
        status=OrderStatus.PENDING_PAYMENT,
        shipping_address=shipping_address,
        shipping_fee=shipping_info.get("total_fee", 0),
        create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    )
    
    MOCK_ORDERS.append(order)
    return order.dict()

@mcp.tool()
def process_payment(order_id: str, payment_method: PaymentMethod) -> Dict:
    """
    处理订单支付
    :param order_id: 订单ID
    :param payment_method: 支付方式
    :return: 支付结果
    """
    order = next((o for o in MOCK_ORDERS if o.id == order_id), None)
    if not order:
        return {"error": "订单不存在"}
    
    if order.status != OrderStatus.PENDING_PAYMENT:
        return {"error": "订单状态不正确"}
    
    # 模拟支付过程
    order.status = OrderStatus.PAID
    order.payment_method = payment_method
    order.pay_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # 更新商品库存
    for item in order.items:
        product = next((p for p in MOCK_PRODUCTS if p.id == item["product_id"]), None)
        if product:
            product.stock -= item["quantity"]
    
    return {
        "order_id": order.id,
        "status": "success",
        "payment_method": payment_method,
        "amount": order.final_amount,
        "pay_time": order.pay_time
    }

@mcp.tool()
def manage_wishlist(user_id: str, action: str, product_id: str = None, note: str = None) -> Dict:
    """
    管理心愿单
    :param user_id: 用户ID
    :param action: 操作类型(add/remove/list)
    :param product_id: 商品ID
    :param note: 备注
    :return: 心愿单信息
    """
    if action == "add":
        product = next((p for p in MOCK_PRODUCTS if p.id == product_id), None)
        if not product:
            return {"error": "商品不存在"}
        
        # 检查是否已在心愿单中
        if not any(w.user_id == user_id and w.product_id == product_id for w in MOCK_WISHLISTS):
            wishlist_item = WishList(
                user_id=user_id,
                product_id=product_id,
                add_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                price_at_add=product.price,
                note=note
            )
            MOCK_WISHLISTS.append(wishlist_item)
    
    elif action == "remove":
        MOCK_WISHLISTS[:] = [w for w in MOCK_WISHLISTS if not (w.user_id == user_id and w.product_id == product_id)]
    
    # 获取用户的心愿单
    user_wishlist = [w.dict() for w in MOCK_WISHLISTS if w.user_id == user_id]
    
    # 添加商品信息
    for item in user_wishlist:
        product = next((p for p in MOCK_PRODUCTS if p.id == item["product_id"]), None)
        if product:
            item["product"] = product.dict()
            item["price_change"] = product.price - item["price_at_add"]
    
    return {
        "user_id": user_id,
        "total": len(user_wishlist),
        "items": user_wishlist
    }

@mcp.tool()
def share_product(user_id: str, product_id: str, content: str, images: List[str] = None) -> Dict:
    """
    分享商品
    :param user_id: 用户ID
    :param product_id: 商品ID
    :param content: 分享内容
    :param images: 图片列表
    :return: 分享结果
    """
    product = next((p for p in MOCK_PRODUCTS if p.id == product_id), None)
    if not product:
        return {"error": "商品不存在"}
    
    share = SocialShare(
        id=f"s{len(MOCK_SHARES)+1}",
        user_id=user_id,
        product_id=product_id,
        content=content,
        images=images or [],
        likes=0,
        comments=[],
        share_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    )
    
    MOCK_SHARES.append(share)
    
    return {
        "share_id": share.id,
        "user_id": user_id,
        "product": product.dict(),
        "content": content,
        "images": images,
        "share_time": share.share_time
    }

@mcp.tool()
def interact_with_share(user_id: str, share_id: str, action: str, comment_content: str = None) -> Dict:
    """
    与分享内容互动
    :param user_id: 用户ID
    :param share_id: 分享ID
    :param action: 操作类型(like/comment)
    :param comment_content: 评论内容
    :return: 互动结果
    """
    share = next((s for s in MOCK_SHARES if s.id == share_id), None)
    if not share:
        return {"error": "分享不存在"}
    
    if action == "like":
        share.likes += 1
    elif action == "comment" and comment_content:
        share.comments.append({
            "user_id": user_id,
            "content": comment_content,
            "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        })
    
    return share.dict()

@mcp.tool()
def get_order_status(order_id: str) -> Dict:
    """
    获取订单状态
    :param order_id: 订单ID
    :return: 订单状态信息
    """
    order = next((o for o in MOCK_ORDERS if o.id == order_id), None)
    if not order:
        return {"error": "订单不存在"}
    
    # 获取物流信息
    shipping_info = None
    if order.status in [OrderStatus.SHIPPING, OrderStatus.DELIVERED, OrderStatus.COMPLETED]:
        try:
            # 模拟获取物流信息
            shipping_info = {
                "tracking_number": "SF1234567890",
                "carrier": "顺丰快递",
                "status": "运输中" if order.status == OrderStatus.SHIPPING else "已送达",
                "timeline": [
                    {"time": order.ship_time, "status": "已发货", "location": "发货仓库"},
                    {"time": order.complete_time, "status": "已送达", "location": "收货地址"}
                ] if order.status == OrderStatus.COMPLETED else [
                    {"time": order.ship_time, "status": "已发货", "location": "发货仓库"}
                ]
            }
        except Exception as e:
            shipping_info = {"error": str(e)}
    
    return {
        "order": order.dict(),
        "shipping_info": shipping_info
    }

if __name__ == "__main__":
    print("Starting E-commerce Assistant MCP server...")
    mcp.run(transport='stdio')  # 启动服务，使用标准输入输出通信